package com.jumi.microservice.service.usercash.admin;

import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.dto.userWallet.WalletInOrOutRequest;
import com.jumi.microservice.entity.CpsUserWallet;
import com.jumi.microservice.enumerate.CpsWalletTypeEnum;
import com.jumi.microservice.enums.FenXiaoType;
import com.jumi.microservice.mapper.CpsUserWalletMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author by mazhao
 * @Classname WalletInOrOutService
 * @Description TODO
 * @Date 2020/7/22 10:47
 */
@Service
public class AdminCpsWalletInOrOutService {

    @Resource
    CpsUserWalletMapper userWalletMapper;
    @Resource
    AdminCapitalDetailsService adminCapitalDetailsService;
    @Resource
    RedisTemplate<String,String> redisTemplate;

    public static final String userLastDayWaitCash = "cpsUserLastDayWaitCash::";

    /**
     * 入账
     *
     * @param request
     * @return
     */

    public ResponseResult<Boolean> walletIn(WalletInOrOutRequest request) {
        CpsUserWallet userWallet = new CpsUserWallet();
        BeanUtils.copyProperties(request, userWallet);
        if(userWallet.getUserLevel()==null){
            List<Integer> userIds = new ArrayList<>();
            userIds.add(request.getUserId().intValue());
            Map<Long, JmUserReponse> userMap = adminCapitalDetailsService.getUserInfoMap(userIds);
            if(userMap.containsKey(request.getUserId())){
                userWallet.setUserLevel(userMap.get(request.getUserId()).getLevel().getValue());
            }
        }
        if(request.getType().equals(CpsWalletTypeEnum.AFTER_SALE_BCK_IN.getCode())){
            userWallet.setRemark("订单补偿，订单编号："+request.getOrderNo());
        }
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        return responseResult.setData(userWalletMapper.insert(userWallet) > 0);
    }

    /**
     * 用户服务批量入账
     *
     * @param list
     * @return
     */
    public Boolean batchWalletIn(List<WalletInOrOutRequest> list) {
        if (list == null || list.isEmpty()) {
            return true;
        }
        for (WalletInOrOutRequest request : list) {
            CpsUserWallet userWallet = new CpsUserWallet();
            BeanUtils.copyProperties(request, userWallet);
            if (request.getType().equals(CpsWalletTypeEnum.SPREAD_IN.getCode())) {
                userWallet.setType(CpsWalletTypeEnum.SPREAD_IN.getCode());
                userWallet.setRemark(CpsWalletTypeEnum.SPREAD_IN.getMsg() + "，订单编号：" + request.getOrderNo());
            } else if (request.getType().equals(CpsWalletTypeEnum.ORDER_IN.getCode())) {
                userWallet.setType(CpsWalletTypeEnum.ORDER_IN.getCode());
                userWallet.setRemark(CpsWalletTypeEnum.ORDER_IN.getMsg() + "，订单编号：" + request.getOrderNo());
            }
            userWalletMapper.insert(userWallet);
        }
        return true;
    }


    /**
     * 出账
     *
     * @param request
     * @return
     */
    public ResponseResult<Boolean> walletOut(WalletInOrOutRequest request) {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        CpsUserWallet userWallet = new CpsUserWallet();
        BeanUtils.copyProperties(request, userWallet);
        if(userWallet.getUserLevel()==null){
            List<Integer> userIds = new ArrayList<>();
            userIds.add(request.getUserId().intValue());
            Map<Long, JmUserReponse> userMap = adminCapitalDetailsService.getUserInfoMap(userIds);
            if(userMap.containsKey(request.getUserId())){
                userWallet.setUserLevel(userMap.get(request.getUserId()).getLevel().getValue());
            }
        }
        BigDecimal balance = userWalletMapper.getBalanceByUserId(userWallet.getUserId()).subtract(userWallet.getAmount());
        if (balance.compareTo(BigDecimal.ZERO) < 0) {
            return responseResult.setData(false);
        }
        userWallet.setAmount(userWallet.getAmount().negate());
        return responseResult.setData(userWalletMapper.insert(userWallet) > 0);
    }

    /**
     * 出入账枚举字典
     *
     * @return
     */
    public Map<Integer, String> dic() {
        CpsWalletTypeEnum[] walletTypeEnums = CpsWalletTypeEnum.values();
        Map<Integer, String> map = new HashMap<>(walletTypeEnums.length);
        for (CpsWalletTypeEnum walletTypeEnum : walletTypeEnums) {
            map.put(walletTypeEnum.getCode(), walletTypeEnum.getMsg());
        }
        return map;
    }

    public BigDecimal waitCash(Long uid) {
        BigDecimal today = userWalletMapper.WaitCashByUserIdToday(uid);
        String key = userLastDayWaitCash.concat(String.valueOf(uid));
        Boolean hasKey = redisTemplate.hasKey(key);
        BigDecimal lastDay;
        if(hasKey!=null && hasKey){
            lastDay = new BigDecimal(redisTemplate.opsForValue().get(key));
        }else{
            lastDay = userWalletMapper.listDayWaitCashByTimeByUid(uid);
            redisTemplate.opsForValue().set(key,lastDay.toString());
        }
        return today.add(lastDay);
    }

    @Scheduled(cron = "0 0 3 * * ?")
//    @Scheduled(fixedDelay = 60 * 60 * 1000)
    public void scheduledWallet(){
        List<Map<String,BigDecimal>> listMap = userWalletMapper.listDayWaitCashByTime();
        for(Map<String,BigDecimal> map:listMap){
            redisTemplate.opsForValue().set(userLastDayWaitCash.concat(String.valueOf(map.get("userId"))),
                    String.valueOf(map.get("amount")));
        }
    }

}
